//============================================================================
// Name        : Connection.cpp
// Author      : O.M.A.V.
// Description : Implementation file van de connection class
//============================================================================

#include "connection.h"
#include <string.h>
#include <pthread.h>

using namespace std;

const int RCVBUFSIZE = 1024;

void HandleTCPClient(TCPSocket *sock);		// TCP client handling function
void *ThreadMain(void *clientSocket);		// Main program of a thread

/*
 * Create a new connection.
 */
Connection::Connection(int port)
{
	TCPSocket serverSocket(port, 5);

	while(1) {
		// Create seperate memory for client argument
		TCPSocket *clientSocket = serverSocket.accept();

		pthread_t threadID;
		if (pthread_create(&threadID, NULL, ThreadMain, (void *) clientSocket) != 0) {
			cerr << "Kan geen thread maken." << endl;
			exit(1);
		}
	}
}

/*
 * TCP Client handling function.
 */
void HandleTCPClient(TCPSocket *sock)
{

	// Receive information and echo it back
	char echoBuffer[RCVBUFSIZE];
	int rcvSize;
	while ((rcvSize = sock->recv(echoBuffer, RCVBUFSIZE)) > 0) { // 0 means end of transmission
		const char msg[] = "Bericht ontvangen!!\n\n";

		string data(echoBuffer);
		string disp = "Ongeldige code";
		if (data == "101") {
			disp = "STOP";
		} else if (data == "102") {
			disp = "VOORUIT";
		} else if (data == "103") {
			disp = "ACHTERUIT";
		} else if (data == "104") {
			disp = "LINKS";
		} else if (data == "105") {
			disp = "RECHTS";
		} else if (data == "201") {
			disp = "Start camera stream";
		} else if (data == "202") {
			disp = "Stop camera stream";
		}

		cout << disp << endl;
		memset(echoBuffer, 0, strlen(echoBuffer));

		// Echo it back
		sock->send(msg);
	}
	cout << endl << endl << "--Verbinding met client verbroken--" << endl << endl;
}

/*
 * Socket receive entry point.
 */
void *ThreadMain(void *clientSocket)
{
	// Deallocate the thread
	pthread_detach(pthread_self());
	cout << endl << "Client verbonden" << endl;

	// Extract socket descriptor from the argument
	HandleTCPClient((TCPSocket *)clientSocket);
	cout << endl << "Verbinding met client verbroken" << endl;

	// Deallocate the socket
	delete (TCPSocket *)clientSocket;
	return NULL;
}
